package MyLinkedStack;

//链式栈：单链式栈

public class MyStack {
    static class ListNode {

        public ListNode next;
        public int val;
        public ListNode(int val){
            this.val = val;
        }
    }

    public int size;
    public ListNode top;

    public void push(int data){
        ListNode node = new ListNode(data);
        node.next = top;
        top = node;
        this.size++;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public int pop() throws EmptyStackException{
        if (isEmpty()){
            throw new EmptyStackException("栈为空，无法弹栈");
        }
        int topVal = top.val;
        top = top.next;
        return topVal;
    }


    public int peek() throws EmptyStackException{
        if (isEmpty()){
            throw new EmptyStackException("栈为空，无法弹栈");
        }
        int topVal = top.val;
        return topVal;
    }

    public void display(){
        ListNode cur = top;
        while(cur != null){
            System.out.print(cur + " ");
            cur = cur.next;
        }
        System.out.println();
    }
}
